import $store from "@/store";

import io from '@/js_sdk/huzhen555-uniappsocketio/uniapp.socket.io.js';

import util from 'utils/util'

import {
	VUE_APP_WS_URL
} from "@/config/app";

let socket = null;
const CONNECT_EVENT = 'connect';
const DISCONNECT_EVENT = 'disconnect';
const RECONNECT_EVENT = 'reconnect';
const HEARTBEAT_EVENT = 'ping';

// 封装websocket连接对象，包含重连和心跳功能
function createSocket(url, options) {
	if (!socket) {
		socket = io(VUE_APP_WS_URL, {
			reconnection: true, // 启用重连
			reconnectionDelay: 1000, // 重连间隔时间
			reconnectionAttempts: Infinity, // 重连次数
			transports: ['websocket'], // 仅使用WebSocket传输
		});
		socket.on(CONNECT_EVENT, () => {
			console.log('WebSocket connected');
			if ($store.state.app.user_id != 0) {
				// console.log('user_id-------' + $store.state.app.user_id)
				socket.emit('login', 'yl_u' + $store.state.app.user_id);
			}
		});
		socket.on(DISCONNECT_EVENT, () => {
			console.warn('WebSocket disconnected');
		});
		socket.on(RECONNECT_EVENT, () => {
			console.log('WebSocket reconnected');
			if ($store.state.app.user_id != 0) {
				socket.emit('login', 'yl_u' + $store.state.app.user_id);
			}
		});
		socket.on(HEARTBEAT_EVENT, () => {
			console.log('ping------');
		});

		// socket.on('pong', function(data) {
		// 	lastPongTime = new Date().getTime();
		// 	console.log('WebSocket ping received------' + util.GMT(lastPongTime))
		// });

	}
	return socket;
}


module.exports = createSocket